import httplib
import re
import time


class SartConnection(object):
    SEESION_ID = None
    def __init__(self, host, log, port='8080', url='/api/xml', method='POST'):
        self.conn = httplib.HTTPConnection('%s:%s' % (host, port))
        self.url = url
        self.method = method
        self.log = log
        """
        try:
            self.execute_command(command, time_to_response)
        finally:
            self.conn.close()
        """

    def execute_command(self, command, time_to_response='0'):
        try:
            self.log._log('INFO: input:\n\r%s' % command)

            if re.search('login', command, re.I):
                response = self._execute_xml_command(command, time_to_response)
                # get the session id from cookie
                try:
                    cookie = response.getheader('set-cookie')
                    SartConnection.SEESION_ID = re.search('.*JSESSIONID=(.*);', cookie).group(1)
                except Exception,  e:
                    print 'no session id is found in cookie (%s)' % cookie
                    raise
            else:
                response = self._execute_xml_command(command, time_to_response)

            output = response.read()
            self.log._log('INFO: output:\n\r%s' % output)
            return output
        except Exception, e:
            self.log._log("ERROR: execute XML command %s failed" % command)
            self.log._log("ERROR: %s" % e)
        finally:
            self.conn.close()



    def _execute_xml_command(self, command, time_to_response='0'):
        headers = {'Content-type': 'text/xml',
                   'Connection': 'keep-alive',
                   'Content-Length': '%d' % len(command)}
        if SartConnection.SEESION_ID:
            headers['Cookie'] = 'JSESSIONID=%s' % SartConnection.SEESION_ID

        self.conn.request(self.method, self.url, command, headers)
        time.sleep(int(time_to_response))

        response = self.conn.getresponse()
        return response